/**
 * 已知如下数组菜单，要求输出树形菜单结构,递归代码实现?
    [
        { id: 1, parent: null, name: '菜单1' },
        { id: 2, parent: 1, name: '菜单1-1' },
        { id: 3, parent: 1, name: '菜单1-2' },
        { id: 4, parent: null, name: '菜单2' },
        { id: 5, parent: 4, name: '菜单2-1' },
    ]

  树形菜单
  [
    {
        id: 1,
        parent: null,
        name: '菜单1',
        children: [
            { id: 2, parent: 1, name: '菜单1-1' },
            { id: 3, parent: 1, name: '菜单1-2' },
        ]
    },
    {
        id: 4,
        parent: null,
        name: '菜单2',
        children: [
            { id: 5, parent: 4, name: '菜单2-1' }
        ]
    }
]
 */
const list = [
    { id: 1, parent: null, name: '菜单1' },
    { id: 2, parent: 1, name: '菜单1-1' },
    { id: 3, parent: 1, name: '菜单1-2' },
    { id: 4, parent: null, name: '菜单2' },
    { id: 5, parent: 4, name: '菜单2-1' },
]

/**
   menuList = [
        { id: 1, parent: null, name: '菜单1', },
        { id: 4, parent: null, name: '菜单2' },
   ]
 */

/**
 * 思路:
 *    遍历数组，找一级节点添加到树型数组
 *    遍历树型数组,递归添加children
 * 
 * @param {*} rootList  一维数组 
 * @param {*} id  父id
 * @param {*} list 返回的树型数组
 */
const getTreeMenu = (rootList, id, menuList) => {
    // 实现方法体
    for(let item of rootList){
        if(item.parent === id){
            menuList.push(item)
        }
    }
    // 添加子菜单节点
    for(let item of menuList){
        item.children = []
        getTreeMenu(rootList,item.id,item.children)
    }
    
    return menuList
}

/**
 * 
 */
let menuList = getTreeMenu(list, null, [])
console.log(menuList)
